﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;

namespace InfonavaEye.components
{

    public  class AutoCloseMessageBox
    {
        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        static extern bool EndDialog(IntPtr hDlg, out IntPtr nResult);

        public static void Show(String msg)
        {
            var caption = "提示";
            ThreadPool.QueueUserWorkItem(new WaitCallback(CloseMessageBox),
                 new CloseState(caption, 4000));
            MessageBox.Show(msg,caption);
        }

        public static void Show(String msg, string caption)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(CloseMessageBox),
                 new CloseState(caption, 4000));
            MessageBox.Show(msg, caption);
        }

        private static void CloseMessageBox(object state)
        {
            CloseState closeState = state as CloseState;

            Thread.Sleep(closeState.Timeout);
            IntPtr dlggg = FindWindow(null, closeState.Caption);

            if (dlggg != IntPtr.Zero)
            {
                IntPtr result;
                EndDialog(dlggg, out result);
            }
        }

        private class CloseState
        {
            private int _Timeout;

            /// <summary>
            /// In millisecond
            /// </summary>
            public int Timeout
            {
                get
                {
                    return _Timeout;
                }
            }

            private string _Caption;

            /// <summary>
            /// Caption of dialog
            /// </summary>
            public string Caption
            {
                get
                {
                    return _Caption;
                }
            }

            public CloseState(string caption, int timeout)
            {
                _Timeout = timeout;
                _Caption = caption;
            }
        }
        
    }
}
